/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lolbatfsm.implementation.io;

import lolbatfsm.io.FSMStore;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import lolbatfsm.system.FSM;

/**
 * It is an implementation of <code>FSMStore</code> which saves the finite-state machines
 * in a file called './fsms.dat'.
 * @author Matteo Battaglio <matteo.battaglio@gmail.com>
 */
public class FSMFileStore implements FSMStore {

    public static final int FSM_COUNT = 2;
    public static final String FSM_FILE_NAME = "./fsms.dat";

    @Override
    public Collection<FSM> loadFSMs() {
        List<FSM> fsms = new LinkedList<FSM>();
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FSM_FILE_NAME));
            FSM fsm;
            while ((fsm = (FSM) ois.readObject()) != null) {
                fsm.init();
                fsms.add(fsm);
            }
            return fsms;
        } catch (EOFException ex) {
            return fsms;
        } catch (IOException ex) {
        } catch (ClassNotFoundException ex) {
        }
        return fsms;
    }

    @Override
    public void storeFSMs(Collection<FSM> fsms) {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FSM_FILE_NAME));
            for (FSM fsm : fsms) {
                oos.writeObject(fsm);
            }
            oos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}
